package com.longyou.comm.admin.controller;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageInfo;
import com.longyou.comm.dto.OperateLogResultDTO;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.cloud.constant.CoreConstant;
import org.cloud.dimension.annotation.SystemResource;
import org.cloud.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/admin/mongo/OperateLog", produces = MediaType.APPLICATION_JSON_VALUE)
@SystemResource(path = "/admin/mongo/OperateLog")
public class MongodbOperateLogController {

    @Autowired
    MongoTemplate mongoTemplate;


    @SystemResource(value = "获取操作日志", description = "管理员后台查询日志，需要授权", authMethod = CoreConstant.AuthMethod.BYUSERPERMISSION)
    // 别放开，swagger会报错，原因待查
//    @ApiImplicitParams({@ApiImplicitParam(name = "microName", value = "微服务名称", required = true), @ApiImplicitParam(name = "type", value = "操作类型"),
//        @ApiImplicitParam(name = "desc", value = "关键字"), @ApiImplicitParam(name = "startTime", value = "开始时间"),
//        @ApiImplicitParam(name = "endTime", value = "结束时间"), @ApiImplicitParam(name = "username", value = "操作人"),
//        @ApiImplicitParam(name = "success", value = "是否成功"),})
    @PostMapping("/list/{page}/{pageSize}")
    public ResponseResult listPage(@PathVariable("page") int page, @PathVariable("pageSize") int pageSize, @RequestBody Map<String, Object> queryParams)
        throws Exception {
        ResponseResult result = ResponseResult.createSuccessResult();
        if (ObjectUtil.isEmpty(queryParams.get("microName"))) {
            return result;
        }
        String collectionName = queryParams.get("microName") + CoreConstant.MongoDbLogConfig.MONGODB_OPERATE_LOG_SUFFIX.value();
        Criteria criteria = new Criteria();
        if (ObjectUtil.isNotEmpty(queryParams.get("username"))) {
            Pattern pattern = Pattern.compile("^.*" + queryParams.get("username") + ".*$");
            criteria.and("userName").regex(pattern);
        }
        if (ObjectUtil.isNotEmpty(queryParams.get("type"))) {
            criteria.and("type").is(Integer.parseInt(String.valueOf(queryParams.get("type"))));
        }
        if (ObjectUtil.isNotEmpty(queryParams.get("desc"))) {
            Pattern pattern = Pattern.compile("^.*" + queryParams.get("desc") + ".*$");
            criteria.orOperator(Criteria.where("resMsg").regex(pattern), Criteria.where("uri").regex(pattern), Criteria.where("reqIp").regex(pattern),
                Criteria.where("params").regex(pattern), Criteria.where("desc").regex(pattern), Criteria.where("reqHeader").regex(pattern),
                Criteria.where("reqHeader").regex(pattern));
        }
        if (ObjectUtil.isNotEmpty(queryParams.get("startTime"))) {
            criteria.and("createDate").gte(strToDateLong(queryParams.get("startTime").toString())).lt(strToDateLong(queryParams.get("endTime").toString()));
        }
//        if (ObjectUtil.isNotEmpty(queryParams.get("endTime"))) {
//            criteria.and("createDate").lt(strToDateLong(queryParams.get("endTime").toString()));
//        }
        if (ObjectUtil.isNotEmpty(queryParams.get("success"))) {
            criteria.and("success").is(Boolean.valueOf(queryParams.get("success").toString()));
        }
        Query query = new Query(criteria);
        Sort.Order createTimeDesc = new Sort.Order(Sort.Direction.DESC, "createDate");
        ArrayList<Order> orders = new ArrayList<>();
        orders.add(createTimeDesc);
        query.with(Sort.by(orders));
        //分页查询数据
        List<OperateLogResultDTO> listData = mongoTemplate.find(query.skip((page - 1L) * pageSize).limit(pageSize), OperateLogResultDTO.class, collectionName);
        PageInfo<?> pageInfo = new PageInfo<>(listData);
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        //查询总页数
        pageInfo.setTotal(mongoTemplate.getCollection(collectionName).countDocuments(query.getQueryObject()));
        result.setData(pageInfo);
        return result;
    }

    public static Date strToDateLong(String strDate) {
        Date strtodate = null;
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            strtodate = formatter.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return strtodate;
    }
}
